<template>
  <div>
    <el-page-header @back="goBack" content="查看章节"> </el-page-header>
    <el-card class="box-card" v-loading="loading">
      <div class="card-title">《{{ novel.bookName }}》小说</div>
      <div>
        <span class="count"
          >总章节数：<span style="color:#409eff">{{
            numForStr(chapterList.length)
          }}</span>
          章</span
        >
        <div style="margin:5px 0px">
          正常状态章节：<span style="color:#67ca3a;">{{
            numForStr(normal)
          }}</span>
          章
        </div>
        <div style="margin:5px 0px">
          下架状态章节：<span style="color:#f56c6c;;">{{
            numForStr(offTheShelfCount)
          }}</span>
          章
        </div>
      </div>
      <div class="chapterBody">
        <div class="drag-item-title ">
          <el-row>
            <el-col class="line" :span="4">
              章节名
            </el-col>
            <el-col class="line" :span="4">
              上架时间
            </el-col>
            <el-col class="line" :span="4">
              字数
            </el-col>
            <el-col class="line" :span="4">
              章节状态
            </el-col>
            <el-col :span="3">
              操作
            </el-col>
          </el-row>
        </div>
        <draggable
          :v-if="chapterList.length > 0"
          v-model="chapterList"
          @update="datadragEnd"
          :options="{ animation: 200 }"
        >
          <div
            :class="'drag-item ' + (item.selectFlag ? 'selectChapter' : '')"
            @mousedown="mousedown(item)"
            @mouseup="mouseup(item)"
            v-for="(item, i) in chapterList"
            :key="i"
          >
            <el-row>
              <el-col class="line" :span="4"
                >&nbsp;{{
                  '第' + numForStr(i + 1) + '章节  ' + item.chapterName
                }}</el-col
              >
              <el-col class="line" :span="4">{{
                item.chapterLaunchTime
              }}</el-col>
              <el-col class="line" :span="4">{{ item.chapterNumber }}</el-col>
              <el-col
                :class="
                  'line ' +
                    (item.chapterStatus == 1 ? 'normal' : 'off-the-shelf')
                "
                :span="4"
                >{{ item.chapterStatus == 1 ? '正常' : '已下架' }}</el-col
              >
              <el-col :span="3">
                <el-button
                  v-if="item.is_system != 1"
                  type="text"
                  size="mini"
                  class="my-el-button-text"
                  @click="deleCode(i, item)"
                  >下架</el-button
                >
                <el-button
                  v-if="item.is_system != 1"
                  type="text"
                  class="my-el-button-text"
                  size="mini"
                  @click="enditCode(i, item)"
                  >修改</el-button
                >
              </el-col>
            </el-row>
          </div>
        </draggable>
      </div>
      <el-dialog title="修改章节" :visible.sync="dialogFormVisible">
        <el-form :model="chapterForm">
          <el-form-item label="小说名称" :label-width="formLabelWidth">
            <el-input
              disabled
              v-model="novel.bookName"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="上架时间" :label-width="formLabelWidth">
            <el-input
              disabled
              v-model="chapterForm.chapterLaunchTime"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="章节名称" :label-width="formLabelWidth">
            <el-input
              v-model="chapterForm.chapterName"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="章节状态" :label-width="formLabelWidth">
            <el-dropdown @command="handleCommand">
              <el-button
                size="small"
                :type="chapterForm.chapterStatus == 1 ? 'success' : 'danger'"
              >
                {{ chapterForm.chapterStatus == 1 ? '正常' : '已下架'
                }}<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item :command="calculation(1, chapterForm)"
                  >正常</el-dropdown-item
                >
                <el-dropdown-item :command="calculation(0, chapterForm)"
                  >已下架</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </el-form-item>
          <el-form-item label="选择文件" :label-width="formLabelWidth">
            <el-upload
              class="upload-demo"
              action=""
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :limit="1"
              :on-exceed="handleExceed"
              :file-list="fileList"
              :http-request="uploadFile"
              accept=".txt"
              :on-success="onSuccess"
              :on-change="onChange"
              :before-upload="beforeUpload"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="字数总数" :label-width="formLabelWidth">
            <el-input
              disabled
              v-model="chapterForm.chapterNumber"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateDetermine">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
import {
  queryChapterLately,
  modifyChapterByBookId
} from '@/network/chapterManager'
import { timeStampFormatStr } from '@/util/dataTimeUtil'
import {
  queryBookById,
  bookModify,
  uploadImg,
  uploadImgTrue
} from '@/network/bookManager'
export default {
  data() {
    return {
      BookChapterSort: [],
      chapterList: [], // 章节对象
      backupsChapterList: [], // 备份章节对象
      novel: {}, // 小说书籍对象
      loading: false,
      selectChapter: { selectFlag: false },
      offTheShelfCount: 0, // 下架总数
      normal: 0, // 正常总数
      dialogFormVisible: false,
      formLabelWidth: '120px',
      chapterForm: {
        _id: '',
        chapterBookId: '',
        chapterContentUrl: '',
        chapterLaunchTime: '',
        chapterName: '',
        chapterNumber: 0,
        chapterStatus: 1
      },
      file: null,
      fileList: [],
      updateIndex: -1 // 被修改的章节下标
    }
  },
  methods: {
    // 返回章节查询
    goBack() {
      this.$router.push({
        path: '/chapterquery'
      })
    },
    // 拖拽排序方法
    async datadragEnd(evt) {
      this.$confirm('此操作将永久修改该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          evt.preventDefault()
          console.log('拖动前的索引 :' + evt.oldIndex)
          console.log('拖动后的索引 :' + evt.newIndex)
          this.loading = true
          let newIndex = evt.newIndex
          // 遍历数组,将索引值赋值到对应的sort_order上面,完成排序
          let arr = this.chapterList

          let newArr = await arr.map((item, i) => {
            return {
              sort_order: i,
              chapterName: item.chapterName,
              chapterLaunchTime: item.chapterLaunchTime,
              _id: item._id
            }
          })
          console.info(newArr)
          let afterChapter = newArr[newIndex + 1]
          let beforeChapter = newArr[newIndex - 1]
          let newChapterLaunchTime = ''
          // 当移到最末尾时
          if (afterChapter == undefined) {
            newChapterLaunchTime =
              new Date(beforeChapter.chapterLaunchTime).getTime() +
              1000 * 60 * 5
          }
          // 当移到最首位时
          if (beforeChapter == undefined) {
            newChapterLaunchTime =
              new Date(afterChapter.chapterLaunchTime).getTime() - 1000 * 60 * 5
          }
          if (afterChapter != undefined && beforeChapter != undefined) {
            newChapterLaunchTime =
              (new Date(afterChapter.chapterLaunchTime).getTime() +
                new Date(beforeChapter.chapterLaunchTime).getTime()) /
              2
          }
          this.chapterList[newIndex].chapterLaunchTime = timeStampFormatStr(
            newChapterLaunchTime
          )
          newArr[newIndex].chapterLaunchTime = timeStampFormatStr(
            newChapterLaunchTime
          )
          await modifyChapterByBookId(newArr[newIndex]) // 修改章节排序
          bookModify({
            // 修改书籍最近修改时间
            _id: this.chapterList[newIndex].chapterBookId,
            bookToUpdate: {
              date: timeStampFormatStr(new Date().getTime())
            }
          })
          this.backupsChapterList = this.chapterList // 修改完成后同步备份
          this.$message.success('修改成功')
          this.loading = false
          console.info(newArr)
        })
        .catch(() => {
          this.chapterList = this.backupsChapterList // 恢复成未修改的样子
          this.$message({
            type: 'info',
            message: '已取消修改'
          })
        })
    },
    // 将 阿拉伯数字123 转换成 字符串数字一二三
    numForStr(n) {
      var cnum = [
        '零',
        '一',
        '二',
        '三',
        '四',
        '五',
        '六',
        '七',
        '八',
        '九',
        '十'
      ]
      var s = ''
      n = '' + n // 数字转为字符串
      for (var i = 0; i < n.length; i++) {
        s += cnum[parseInt(n.charAt(i))]
      }
      if (s.length == 2) {
        // 两位数的时候
        // 如果个位数是0的时候，令改成十
        if (s.charAt(1) == cnum[0]) {
          s = s.charAt(0) + cnum[10]
          // 如果是一十改成十
          if (s == cnum[1] + cnum[10]) {
            s = cnum[10]
          }
        } else if (s.charAt(0) == cnum[1]) {
          // 如果十位数是一的话改成十
          s = cnum[10] + s.charAt(1)
        }
      }
      return s
    },
    // 修改按钮
    enditCode(i, item) {
      this.updateIndex = i
      console.info(i)
      console.info(item)

      this.chapterForm = JSON.parse(JSON.stringify(item))
      let fileName = this.chapterForm.chapterContentUrl.substring(
        this.chapterForm.chapterContentUrl.lastIndexOf('/') + 1,
        this.chapterForm.chapterContentUrl.lastIndexOf('.')
      )
      let fileNames= fileName.split('-')
      let file = {
        name: fileNames[1]||fileNames[0],
        url: this.chapterForm.chapterContentUrl
      }
      this.fileList = []
      this.fileList.push(file)
      this.dialogFormVisible = true
    },
    // 删除章节
    deleCode(i, item) {
      if (item.chapterStatus == 0) {
        return this.$message.warning('该章节已是下架状态')
      }
      this.$confirm('此操作将下架该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          item.chapterStatus = 0
          modifyChapterByBookId(item)
          this.normal--
          this.offTheShelfCount++
          this.backupsChapterList = this.chapterList
          this.loading = false
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 点击改变颜色
    mousedown(item) {
      this.selectChapter.selectFlag = false
      this.selectChapter = item
      item.selectFlag = true
    },
    // 松开鼠标 取消样式
    mouseup(item) {
      item.selectFlag = false
    },
    // 自定义上传方法
    async uploadFile() {
      let file = this.file
      console.info(file.raw.type)
      console.info(this.file)
      const imgName = (
        `boxContent/${this.novel.bookName}/` +
        new Date().getTime() +'-'+
        file.name
      ).replace('.txt', '.json')

      let res = await uploadImg(imgName)
      console.info(res)
      // 将返回的地址 处理成代理地址
      let website = res.url.substring(0, res.url.indexOf('com') + 3)
      let trueUrl = res.url.replace(website, '/img')
      // 将数据封装成 formData
      const formData = new FormData()
      formData.append('Signature', res.authorization)
      formData.append('key', imgName)
      formData.append('x-cos-security-token', res.token)
      formData.append('x-cos-meta-fileid', res.cos_file_id)
      formData.append('file', file.raw)

      uploadImgTrue(trueUrl, formData) // 最后一步上传图片
      const fileUrl = `https://7a68-zhuma-mbnti-1302831863.tcb.qcloud.la/${imgName}`
      this.chapterForm.chapterContentUrl = fileUrl // 将图片路径 存入表单对象中
      console.info(fileUrl)
    },
    // 文件改变方法
    onChange(file, fileList) {
      this.file = file
      this.fileList = fileList
    },
    // 文件移除时的 钩子
    handleRemove(file, fileList) {
      console.log(file, fileList)
      this.chapterForm.chapterNumber = ''
      this.file = null
    },
    // 文件超出限制 钩子
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    // 文件删除之间钩子
    beforeRemove(file) {
      console.info(file)
      if(this.fileList[0].uid==file.uid){
        this.fileList.splice(0,1)
      }
      // return this.$confirm(`确定移除 ${file.name}？`)
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      console.log(file)
    },
    // 上传成功后的回调
    onSuccess(resp, file) {
      this.$message.success('文件上传成功')
      let reader = new FileReader()
      if (typeof FileReader === 'undefined') {
        this.$message({
          type: 'info',
          message: '您的浏览器不支持FileReader接口'
        })
        return
      }
      reader.readAsText(file.raw)
      reader.onload = e => {
        let res = e.target.result
        this.chapterForm.chapterNumber = res.length
      }
      console.info(file)
    },
    // 上传之前钩子
    beforeUpload(file) {
      console.info('撒打算')
      if (file.size / 1204 > 500) {
        this.$message.warning('文件大小不能超过500kb')
        return false
      }
    },
    // 下拉菜单触发的方法
    handleCommand(row) {
      if (row.status != row.item.chapterStatus) {
        row.item.chapterStatus = row.status
      }
      console.info(row)
    },
    // 修改确定
    updateDetermine() {
      if(this.fileList.length==0){
        return this.$message.warning('请选择章节文件')
      }
      this.$confirm('此操作将永久修改该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.info(this.chapterForm)
          console.info(this.updateIndex)
          // 当修改对象 状态与原对象 状态不一样时
          if (
            this.chapterForm.chapterStatus !=
            this.chapterList[this.updateIndex].chapterStatus
          ) {
            if (
              this.chapterList[this.updateIndex].chapterStatus == 0 &&
              this.chapterForm.chapterStatus == 1
            ) {
              // 上架状态
              this.normal++
              this.offTheShelfCount--
            } else {
              // 下架状态s
              this.normal--
              this.offTheShelfCount++
            }
          }
          this.chapterList[this.updateIndex] = this.chapterForm
          this.$message.success('修改成功')
          this.dialogFormVisible = false
          modifyChapterByBookId(this.chapterList[this.updateIndex])
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消修改'
          })
        })
    },
    // 计算属性
    calculation(status, item) {
      return {
        status,
        item
      }
    }
  },
  async mounted() {
    this.loading = true
    let novelId = this.$route.params.novelId
    this.chapterList = []
    //   this.dialogTableVisible = true
    this.dialogLoading = true
    queryBookById(novelId).then(res => {
      this.novel = JSON.parse(res.data[0])
    })
    // 查询章节
    queryChapterLately(novelId, '', 'asc').then(res => {
      for (let rs in res.data) {
        let obj = JSON.parse(res.data[rs])
        obj.chapterLaunchTime = timeStampFormatStr(obj.chapterLaunchTime.$date)
        obj.selectFlag = false // 标记是否选中
        this.chapterList.push(obj)
        if (obj.chapterStatus == 1) {
          this.normal++
        } else {
          this.offTheShelfCount++
        }
        this.backupsChapterList = this.chapterList // 备份章节集合
      
      }
        this.loading = false
    })

    console.info(this.chapterList)
    console.info(novelId)
  }
}
</script>
<style lang="less" scoped>
.drag-item {
  padding-top: 7px;
  border-top: 1px solid rgb(226, 223, 223);
}
.drag-item:last-child {
  border-bottom: 1px solid rgb(226, 223, 223);
}
.drag-item-title {
  border-top: none;
  padding-bottom: 10px;
}
.box-card {
  margin-top: 20px;
}
.el-col-6 {
  width: 200px;
  height: 100%;
}
.chapterBody {
  margin: 10px 10px;
}
.selectChapter {
  color: #fd7c27;
}
.count {
  display: inline-block;
  margin: 5px 0px 5px 5px;
}
.normal {
  color: #67ca3a;
}
.off-the-shelf {
  color: #f56c6c;
}
</style>
